import { del, get } from '@/utils/request'
import { Button, Message, Modal, Space, Table, TableColumnProps } from '@arco-design/web-react'
import { useEffect, useRef, useState } from 'react'
import MonitorForm, { ChildRef } from './form'
const Monitor = () => {
  const [visible, setVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)

  const [dialogData, setDialogData] = useState({})

  const form = useRef<ChildRef>(null)
  const columns: TableColumnProps[] = [
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '年龄',
      dataIndex: 'age'
    },
    {
      title: '性别',
      dataIndex: 'gender',
      render: (_, record) => (record.gender === 1 ? '男👦' : '女👧')
    },
    {
      title: '邮箱',
      dataIndex: 'email'
    },
    {
      title: '电话',
      dataIndex: 'phone'
    },
    {
      title: '地址',
      dataIndex: 'address'
    },
    {
      title: '操作',
      dataIndex: 'op',
      render: (_, record) => (
        <Space>
          <Button onClick={() => editRow(record)} type="primary" size="small">
            编辑
          </Button>
          <Button onClick={() => removeRow(record.id)} type="primary" status="danger" size="small">
            删除
          </Button>
        </Space>
      )
    }
  ]
  const [data, setData] = useState([])
  const removeRow = async (key: string) => {
    try {
      await del(`/api/v1/user/${key}`)
      setData(data.filter((item: { id: string }) => item.id !== key))
      Message.success('删除成功')
    } catch (error) {
      /* empty */
    }
  }
  const editRow = (record: Record<string, any>) => {
    setDialogData(record)
    setVisible(true)
  }
  const onSubmit = async () => {
    setConfirmLoading(true)
    try {
      await form.current?.handleSubmit()
    } finally {
      setConfirmLoading(false)
    }
  }
  const afterCloseHandler = () => {
    form.current?.clearFields()
  }
  useEffect(() => {
    // 查询
    const featchList = async () => {
      const data = (((await get('/api/v1/user')) as any) || []).map((item: any) => {
        const { profile, ...res } = item
        return {
          ...profile,
          ...res
        }
      })

      data && setData(data)
      console.log('%c [ data ]-90', 'font-size:13px; background:#1e09ba; color:#624dfe;', data)
    }
    featchList()
  }, [])

  return (
    <>
      <Table columns={columns} data={data} rowKey={(record) => record.id} />
      <Modal
        title="Modal Title"
        confirmLoading={confirmLoading}
        visible={visible}
        onOk={() => onSubmit()}
        onCancel={() => setVisible(false)}
        afterClose={() => afterCloseHandler()}
        autoFocus={false}
        focusLock={true}
      >
        <MonitorForm ref={form} data={dialogData} />
      </Modal>
    </>
  )
}

export default Monitor
